package com.shop.util;

import com.shop.constant.ScheduleConstants;
import com.shop.model.dto.Job;
import org.quartz.*;

/**
 * 定时任务工具类
 *
 * @author ruoyi
 */
public class ScheduleUtils {
    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, Job job) throws SchedulerException, ClassNotFoundException {
        Class<? extends org.quartz.Job> jobClass = (Class<? extends org.quartz.Job>) Class.forName(job.getJobClassName());
        // 构建job信息
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobName(),job.getJobGroup()).build();

        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(),job.getJobGroup())
                .withSchedule(cronScheduleBuilder).build();

        // 放入参数，运行时的方法可以获取
        // jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);

        // 判断是否存在
        if (scheduler.checkExists(getJobKey(job.getJobName(),job.getJobGroup()))) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(job.getJobName(),job.getJobGroup()));
        }

        scheduler.scheduleJob(jobDetail, trigger);
        // 暂停任务
        if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(job.getJobName(),job.getJobGroup()));
        }
    }
    /**
     * 构建任务键对象
     */
    public static JobKey getJobKey(String jobId, String jobGroup)
    {
        return JobKey.jobKey(jobId, jobGroup);
    }
}
